<script lang="ts" setup>
// 获取屏幕边界到安全区域距离
import {useUserStore} from "@/stores/user";
import {onMounted, ref} from "vue";
import type {User} from "@/types/user";
import {getUserAvatarCountApi, updateUserInfoApi} from "@/api/user";
import {IMessage} from "@/components/aw-message/message";

const {safeAreaInsets} = uni.getSystemInfoSync()

const userStore = useUserStore()
const profile = ref<User>({} as User)
profile.value = {...userStore.userInfoData!}

// 点击复制id
const onCopyId = () => {
  uni.setClipboardData({
    data: profile.value!.userID.toString(),
    success: () => {
      uni.showToast({title: '复制成功'})
    }
  })
}

// 修改头像
const tempPath = ref('')
const modifyAvatar = () => {
  if (avatarCount.value < 1) {
    return IMessage({
      type: 'error',
      showIcon: true,
      content: '本周剩余修改头像次数不足',
    })
  }
  uni.navigateTo({url: '/subPkg/profile/avatarCut'})
  // #ifdef H5
  uni.chooseImage({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    success: (res: any) => { // It's hard to find a type here
      if (res.tempFiles[0].size > 5 * 1024 * 1024) {
        return uni.showToast({title: '图片大小不能超过5MB', icon: 'none'})
      }
      tempPath.value = res.tempFiles[0].path
      uni.showLoading({title: '上传中'})
      uni.uploadFile({
        url: '/upload',
        name: 'file',
        filePath: res.tempFiles[0].path,
        timeout: 10000,
        header: {
          'Avatar': userStore.userInfoData!.userID
        },
        success(res) {
          // 判断是否上传成功
          const resultData = JSON.parse(res.data)
          if (resultData.code === '1') {
            // 上传成功，可以更新本地store
            uni.hideLoading()
            profile.value!.avatarURL = JSON.parse(res.data).data
            userStore.userInfoData!.avatarURL = profile.value.avatarURL
            getUserRemainAvatarChangeTimes()
            uni.showToast({title: '头像上传成功', duration: 3000})
            return
          }
          uni.showToast({
            title: resultData.message || '头像上传失败，请稍后重试',
            icon: 'none',
            duration: 3000
          })
        },
        fail(err) {
          uni.hideLoading()
          uni.showToast({
            title: '头像上传失败,请稍后重试',
            icon: 'error',
          })
        }
      })
    }
  })
  // #endif

}

// 点击提交
const onSubmit = async () => {
  // 先判断是否填写完整，昵称是必填项
  if (!profile.value!.username) {
    return uni.showToast({title: '昵称不能为空', icon: 'none'})
  }
  // 判断该信息与原信息是否有改动
  if (JSON.stringify(profile.value) === JSON.stringify(userStore.userInfoData)) {
    await uni.showToast({title: '信息未改动', icon: 'none'})
    uni.navigateBack()
    return
  }
  await uni.showLoading({title: '提交修改中...'})
  // 调用修改个人信息接口
  const updateInfo = {
    username: profile.value!.username,
    email: profile.value!.email,
    phone: profile.value!.phone,
    avatarURL: userStore.userInfoData!.avatarURL,
    individualResume: profile.value!.individualResume
  }
  const res = await updateUserInfoApi(updateInfo)
  if (res.code !== '1') {
    uni.hideLoading()
    return uni.showToast({title: res.message, icon: 'none'})
  }
  uni.hideLoading()
  // 修改本地仓库
  userStore.userInfoData!.username = profile.value!.username
  userStore.userInfoData!.email = profile.value!.email
  userStore.userInfoData!.phone = profile.value!.phone
  userStore.userInfoData!.avatarURL = profile.value!.avatarURL
  userStore.userInfoData!.individualResume = profile.value!.individualResume
  // 返回上一页
  await uni.showToast({title: '信息修改成功', icon: 'success'})
}

// 获取用户本周剩余头像修改次数
const avatarCount = ref(0)
const getUserRemainAvatarChangeTimes = async () => {
  const res = await getUserAvatarCountApi()
  avatarCount.value = res.data
}
onMounted(() => {
  getUserRemainAvatarChangeTimes()
})
uni.$on("updateAvatarFail", () => {
  avatarCount.value = 0
})
const onCancelUpdateAvatar = () => {

}


</script>

<template>
  <view class="viewport">
    <view class="color-change-2x" style="width: 100%;min-height: 400rpx">
      <!-- 导航栏 -->
      <view :style="{ paddingTop: safeAreaInsets?.top + 'px' }" class="navbar">
        <navigator class="back icon-left" hover-class="none" open-type="navigateBack"></navigator>
        <view class="title">个人信息</view>
      </view>
      <!-- 头像 -->
      <view class="avatar">
        <view class="avatar-content">
          <image :src="userStore.userInfoData?.avatarURL||'/static/kun.png'" class="image" mode="aspectFill"
                 @click="modifyAvatar"/>
          <text class="text">点击修改头像</text>
        </view>
        <text class="text-white padding-tb-sm" style="font-size: 10px">本周剩余头像修改次数：
          <text class="text-red">{{ avatarCount }}</text>
        </text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account margin-right-xl">{{ userStore.userInfoData?.userID }}</text>
          <text class="cuIcon-copy line-awGreen " style="font-size: 42rpx" @click="onCopyId"></text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input
              v-model="profile.username"
              class="input"
              placeholder="请填写昵称"
              type="text"
          />
        </view>
        <view class="form-item">
          <text class="label">签名</text>
          <input
              v-model="profile.individualResume"
              class="input"
              placeholder="请填写签名"
              type="text"
          />
        </view>
        <view class="form-item">
          <text class="label">邮箱</text>
          <input
              v-model="profile.email"
              class="input"
              placeholder="请填写邮箱"
              type="text"
          />
        </view>
        <view class="form-item">
          <text class="label">手机号</text>
          <input
              v-model="profile.phone"
              class="input"
              placeholder="请填写手机号"
              type="text"
          />
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button bg-gradual-awGreen" @click="onSubmit">保 存</button>
    </view>

  </view>

</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.color-change-2x {
  animation: color-change-2x 2s linear infinite alternate both;
}

@keyframes color-change-2x {
  0% {
    background: #39c5bb;
  }
  100% {
    background: #3ebed3;
  }
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-size: auto 420rpx;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #39c5bb;
  }
}
</style>
